/**
 Author: 蒋鑫强
 Time: 2023/6/6
 Description:
 */
import fs from 'node:fs';
import { type } from '@/util/util';
import path from 'node:path';
import mergeImages from 'merge-images';
const archiver = require('archiver');
const xlsx = require("node-xlsx");
const pdf = require('pdf-poppler');
const { Buffer } = require('node:buffer');

let timer = null;

export default {
  async zip(files) {
    const output = fs.createWriteStream('tmp/files.zip');
    const archive = archiver('zip', {zlib: {level: 9}});// 设置压缩等级

    archive.pipe(output);

    files.forEach(d => {
      const stream = fs.createReadStream(d.url);
      archive.append(stream, {name: d.name});
    });

    await archive.finalize();

    return 'tmp/files.zip';
  },

  async downloadFile(file) {
    const eleLink = document.createElement('a');
    eleLink.download = file.name;
    eleLink.style.display = 'none';

    if (type.isArray(file)) {
      eleLink.href = await this.zip(file);
      eleLink.download = 'files.zip';
    } else {
      eleLink.href = file.url;
    }

    document.body.appendChild(eleLink);
    eleLink.click();
    document.body.removeChild(eleLink);
  },

  downloadFileByText(name, text) {
    const eleLink = document.createElement('a');
    eleLink.download = name;
    eleLink.style.display = 'none';
    const blob = new Blob([text]);
    eleLink.href = URL.createObjectURL(blob);
    document.body.appendChild(eleLink);
    eleLink.click();
    document.body.removeChild(eleLink);
  },

  findFile(filePath, includes = [], callback) {
    fs.readdir(filePath, (err, files) => {
      if (err) {
        console.error(err, "读取文件夹错误！")
      } else {
        //遍历读取到的文件列表
        files.forEach(filename => {
          //获取当前文件的绝对路径
          const filedir = path.join(filePath, filename);
          //根据文件路径获取文件信息，返回一个fs.Stats对象
          if (!filedir.includes('node_modules')) {
            fs.stat(filedir, (eror, stats) => {
              if (eror) {
                console.error('获取文件stats失败');
              } else {
                const isFile = stats.isFile(); //是文件
                const isDir = stats.isDirectory(); //是文件夹
                timer && clearTimeout(timer);
                if (isFile) {
                  const hasIn = includes.find(d => filedir.includes(d));
                  if (includes.length === 0 || hasIn) {
                    const data = fs.readFileSync(filedir,'utf-8');
                    callback && callback(data, filedir, false);
                  }
                }
                if (isDir) {
                  this.findFile(filedir, includes,  callback); //递归，如果是文件夹，就继续遍历该文件夹下面的文件
                }

                timer = setTimeout(() => {
                  callback && callback('', '', true);
                }, 2000);
              }
            })
          }
        });
      }
    });
  },

  readExcel(path) {
    let list = xlsx.parse(path);
    return list[0].data;
  },

  async pdfToImg(filePath, size = 1024) {
    const opts = {
      format: 'png',
      out_dir: 'tmp',
      out_prefix: `${path.basename(filePath, path.extname(filePath))}`,
      page: null,
      scale: size
    }

    await pdf.convert(filePath, opts);
    return `${opts.out_dir}/${opts.out_prefix}-1.${opts.format}`;
  },

  async imgDraw(basePath, drawPath, size = {x: 0, y: 0, width: 400}) {
    const base64 = await mergeImages([
      {src: basePath, x: 0, y: 0},
      {src: drawPath, x: size.x, y: size.y, width: size.width}
    ]);
    const dataMiniURLBase64 = base64.replace(/^data:image\/\w+;base64,/, '');
    const dataMiniBuffer = Buffer.from(dataMiniURLBase64, 'base64');
    const savePath = drawPath.replace('-1', '');
    await this.writeFile(savePath, dataMiniBuffer);
    await this.remove(drawPath);
    return {
      name: path.basename(savePath),
      url: savePath
    };
  },

  remove(path) {
    return new Promise(resolve => {
      fs.unlink(path, err => {
        if (err) {
          console.error(err);
        }
        resolve();
      })
    });
  },

  writeFile(path, data) {
    return new Promise(resolve => {
      fs.writeFile(path, data, err => {
        if(err){
          console.error(err);
        }
        resolve();
      });
    });
  },

  async readFile(path) {
    return new Promise(resolve => {
      fs.readFile(path, 'utf-8', (err, data) => {
        if (err) {
          console.log(err);
        }
        resolve(data);
      });
    });
  }
};
